//
//  MeatMarketSectionView.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/15.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#define selfH 37
#define mAnimationTime 0.5f
#define mCellHeight 48.f
#define mGap 15.f
#define itemW (KScreenWidth - 5*mGap)/4.0

#import "MeatBuySectionView.h"
#import "CustomScreenMenuModel.h"
#import "CustomCollectionViewCell.h"
#import "CustomSendTimeCollectionCell.h"
#import "CustomCollectionSection.h"
#import "CustomCollectionFooter.h"
#import "STPickerDate.h"

@interface MeatBuySectionView ()<UICollectionViewDelegate, UICollectionViewDataSource, STPickerDateDelegate>


/**
 BuyMeat SectionView's DiamondIcon - >UIImageView
 */
@property (nonatomic, strong) UIImageView *diamondIcon;


/**
 BuyMeat SectionView's RecommendedShopIcon - >UIImageView

 */
@property (nonatomic, strong) UIImageView *recommendedShopIcon;


/**
 BuyMeat SectionView's CartBtn - >UIButton
 */
@property (nonatomic, strong) UIButton *cartBtn;


/**
 BuyMeat SectionView's SwitchBtn - >UIButton
 */
@property (nonatomic, strong) UIButton *switchBtn;


/**
 BuyMeat SectionView's ScreeningBtn - >UIButton
 */
@property (nonatomic, strong) UIButton *screeningBtn;


@property (nonatomic, strong) UIView *redView;


@property (nonatomic, strong) UIView *contentView;
@property (nonatomic, assign) CGFloat offsetY; //偏移量

@property (nonatomic, assign) NSInteger currentIndex;
@property (nonatomic, strong) NSIndexPath *currentIndexPath;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;

@property (nonatomic, strong) UITapGestureRecognizer *tap;

@property (nonatomic, assign) BOOL selected;

@property (nonatomic, strong) NSMutableArray *dates;

@property (nonatomic, assign) NSInteger index;

@property (nonatomic, strong) MeatShopListParam *params;


@end

@implementation MeatBuySectionView

/**
 这个方法相当于vc中的viewDidLoad
 */
- (void)didMoveToWindow {
    if (self.window) {
        [kNotificationCenter addObserver:self selector:@selector(hiddenView) name:KMeatMarketCleanScreeningNotification object:nil];
    }
}


/**
 从当前window删除 相当于-viewDidUnload
 */
- (void)willMoveToWindow:(UIWindow *)newWindow {
    if (newWindow == nil) {
        //移除通知
        [kNotificationCenter removeObserver:self name:KMeatMarketCleanScreeningNotification object:nil];
    }
}


#pragma mark - lifecycle methods
- (void)setupUI{
    
    [self addSubview:self.diamondIcon];
    [self addSubview:self.recommendedShopIcon];
    [self addSubview:self.cartBtn];
    [self addSubview:self.switchBtn];
    [self addSubview:self.screeningBtn];
    
    self.selected = NO;
    self.index = 0;
    
    [self addDropMenuView];
}


- (void)setupLayout{
    
    self.height = selfH;
    
    {
        _diamondIcon.size = CGSizeMake(15, 15);
        _diamondIcon.mj_x = 18;
        _diamondIcon.mj_y = (self.height - _diamondIcon.height)/2.0;
    }
    
    
    {
        _recommendedShopIcon.size = CGSizeMake(63, 15);
        _recommendedShopIcon.mj_y = _diamondIcon.mj_y;
        _recommendedShopIcon.mj_x = _diamondIcon.right + 6;
    }
    
    
    {
        _screeningBtn.size = CGSizeMake(selfH, selfH);
        _screeningBtn.mj_y = (self.height - _screeningBtn.height)/2.0;
        _screeningBtn.mj_x = self.right - _screeningBtn.width - 18;
    }
    
    
    {
        _switchBtn.size = CGSizeMake(selfH, selfH);
        _switchBtn.mj_y = _screeningBtn.mj_y;
        _switchBtn.mj_x = _screeningBtn.left - _switchBtn.width - 13;
    }
    
    
    {
        _cartBtn.size = CGSizeMake(selfH, selfH);
        _cartBtn.mj_y = _screeningBtn.mj_y;
        _cartBtn.mj_x = _switchBtn.left - _cartBtn.width - 13;
        
        _redView.mj_x = _cartBtn.width/3.0 *2;
        _redView.mj_y = 5;
    }
    
    self.currentIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    
    //展开TableView的偏移量
    self.offsetY = TJ_StatusBarHeight_Define + 120 + 42 + self.height ;
    
    //tableView.mj_y
    self.collectionView.mj_y = _offsetY;

}


/**
 添加展示层
 */
- (void)addDropMenuView{
    
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [window addSubview:self.contentView];
    [window addSubview:self.collectionView];
    [window addSubview:self.tableView];
    
    self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenView)];
}

- (void)hiddenView{
    [self dissView];
    
    self.selected = !self.selected;
    UIImage *image = [UIImage imageNamed:@"meat_buy_screen_gray"];
    [self.screeningBtn setImage:image forState:UIControlStateNormal];
}


#pragma mark - public methods

- (void)showView{
    
    [self.collectionView reloadData];
   // UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    [self.contentView addGestureRecognizer:self.tap];

    
    @weakify(self);
    [UIView animateWithDuration:mAnimationTime animations:^{
        @strongify(self);
        
        self.collectionView.hidden = NO;
        self.collectionView.frame = CGRectMake(0, self.offsetY, KScreenWidth, KScreenHeight - (self.offsetY +TJ_TabBarHeight+50));
        self.contentView.frame = CGRectMake(0, self.offsetY, KScreenWidth, KScreenHeight - self.offsetY);
        
        
    } completion:^(BOOL finished) {
        
        self.contentView.alpha = 1;
    }];
}


- (void)dissView{
    
    self.contentView.alpha = 0;
    [self.contentView removeGestureRecognizer:self.tap];

    
    @weakify(self);
    [UIView animateWithDuration:mAnimationTime animations:^{
        @strongify(self);
        if (self.collectionView.height >0) {
            self.collectionView.frame = CGRectMake(0, self.offsetY, KScreenWidth, 0);
        }
        
        if (self.contentView.height >0) {
            self.contentView.frame = CGRectMake(0, self.offsetY, KScreenWidth, 0);
        }
    }];
    
}


- (void)removeScreenView{
    
    if (self.tableView) {
        self.tableView.hidden = YES;
        [self.tableView removeFromSuperview];
    }
    
    if (self.collectionView) {
        self.collectionView.hidden = YES;
        [self.collectionView removeFromSuperview];
    }
    
    if (self.contentView) {
        self.contentView.hidden = YES;
        [self.contentView removeFromSuperview];
    }
}


#pragma mark - date.delegate

- (void)pickerDate:(STPickerDate *)pickerDate year:(NSInteger)year month:(NSInteger)month day:(NSInteger)day{
    
    NSString *date =  [NSString stringWithFormat:@"%ld-%ld-%ld",(long)year,(long)month,(long)day];
    int compare = [NSString compareDateByDate:date];
    if (compare == -1 ) {
        [self.viewController showHudWithMsg:@"请选择正确的时间"];
        return;
    }
    
    if (self.index == 0) {
        
        if ([self.dates[1] isEqualToString:@"结束时间"]) {
            self.params.startTime = date;
        }else{
            
            int result = [NSString compareDate:date withDate:self.dates[1]];
            if (result == 1) {
                self.params.startTime = date;
            }
            else{
                [self.viewController showHudWithMsg:@"请选择正确的时间"];
                return;
            }
        }
    }else {
        
        if ([self.dates[0] isEqualToString:@"开始时间"]) {
            self.params.endTime = date;
        }else{
            
            int result = [NSString compareDate:self.dates[0] withDate:date];
            if (result == 1) {
                self.params.endTime = date;
            }
            else{
                [self.viewController showHudWithMsg:@"请选择正确的时间"];
                return;
            }
        }
    }
    
    [self.dates replaceObjectAtIndex:self.index withObject:date];

    [UIView performWithoutAnimation:^{
        [self.collectionView reloadData];
    }];
    
}


#pragma mark - collectionview.delegate

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return self.model.screens.count;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    ScreenItem *item = self.model.screens[section];
    return item.subTitles.count;
}


- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
    if(section == self.model.screens.count -1)
    {
        CGSize size = {KScreenWidth, 78};
        return size;
    }else{
        
        CGSize size = {KScreenWidth, 0};
        return size;
    }
}


- (CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath{
    
    if (indexPath.section == 2) {
        CGSize size = {KScreenWidth - 30, 45};
        return size;
    }else{
        CGSize size = {itemW, 45};
        return size;
    }
}


- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    if (kind == UICollectionElementKindSectionHeader) {
        
        CustomCollectionSection *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        
        ScreenItem *item = self.model.screens[indexPath.section];
        header.label.text = [NSString stringWithFormat:@"%@", item.title];
        
        return header;
        
    }else{
        
        CustomCollectionFooter *footer = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"footer" forIndexPath:indexPath];
        
#pragma mark - 确定
        @weakify(self);
        footer.dealOkBlock = ^{
            @strongify(self);
            [self hiddenView];
            if (self.resetDataBlock) {
                self.resetDataBlock(self.params);
            }
        };
        
#pragma mark - 重置
        footer.dealReSetBlock = ^{
            @strongify(self);
            [self.model.screens enumerateObjectsUsingBlock:^(ScreenItem * _Nonnull item, NSUInteger idx, BOOL * _Nonnull stop) {
                
                NSMutableArray *aims = [NSMutableArray arrayWithArray:item.tags];

                [item.tags enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if (idx == 0) {
                        [aims replaceObjectAtIndex:idx withObject:@1];
                        
                    }else{
                        [aims replaceObjectAtIndex:idx withObject:@0];
                    }
                }];
                
                item.tags = [aims copy];
            }];
            
            self.dates = [NSMutableArray arrayWithArray:@[@"起始时间",@"结束时间"]];
            {
                self.params.page = @1;
                self.params.limit = @10;
                self.params.tribeId = @2;
                self.params.sex = nil;
                self.params.startTime = nil;
                self.params.endTime = nil;
                self.params.pigPositionIds = nil;
                self.params.varietiesId = nil;
                self.params.isFriend = nil;
                
            }
            
            [UIView performWithoutAnimation:^{
                [self.collectionView reloadData];
            }];
        };
        return footer;
        
    }
    return nil;
}

- (void)showDatePicker {
    STPickerDate *pickerDate = [[STPickerDate alloc]init];
    [pickerDate setYearLeast:[NSDate obtainCurrentYear] - 70];
    [pickerDate setYearSum:71];
    [pickerDate setDelegate:self];
    [pickerDate setHeightPickerComponent:40];
    pickerDate.borderButtonColor = [UIColor primaryColor];
    [pickerDate.buttonRight setTitleColor:[UIColor primaryColor] forState:UIControlStateNormal];
    [pickerDate.buttonLeft setTitleColor:[UIColor textBlackColor] forState:UIControlStateNormal];
    pickerDate.buttonLeft.layer.borderColor = [UIColor clearColor].CGColor;
    pickerDate.buttonRight.layer.borderColor = [UIColor clearColor].CGColor;
    [pickerDate show];
    
}


- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.section == 2) {
        
        CustomSendTimeCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomSendTimeCollectionCell" forIndexPath:indexPath];
        cell.dates = self.dates;
        
        //起始时间
        cell.dealStartBlock = ^{
            self.index = 0;
            [self showDatePicker];
        };
        
        //结束时间
        cell.dealEndBlock = ^{
            self.index = 1;
            [self showDatePicker];
        };
        return cell;
    }
    
    CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CustomCollectionViewCell" forIndexPath:indexPath];
    
    ScreenItem *item = self.model.screens[indexPath.section];
    cell.label.text = [NSString stringWithFormat:@"%@", item.subTitles[indexPath.item]];
    cell.isChoosed = [item.tags[indexPath.item] isEqual:@1] ?YES :NO;
    
    return cell;
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ScreenItem *item = self.model.screens[indexPath.section];
    
    NSMutableArray *aims = [NSMutableArray arrayWithArray:item.tags];
    [item.tags enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (indexPath.section != 3) {
            if (idx == indexPath.item) {
                [aims replaceObjectAtIndex:idx withObject:@1];
            }else if (idx != indexPath.item && [obj isEqual:@1]){
                [aims replaceObjectAtIndex:idx withObject:@0];
            }
        }else{
            
            if (indexPath.item == 0) {
                
                if (idx == 0) {
                    [aims replaceObjectAtIndex:idx withObject:@1];

                }else{
                    [aims replaceObjectAtIndex:idx withObject:@0];
                }
            }else{
                
                if (idx == indexPath.item) {
                    
                    NSNumber *indexObject = [obj isEqual:@1] ?@0 :@1;
                    [aims replaceObjectAtIndex:idx withObject:indexObject];
                    
                }else if (idx == 0 && [obj isEqual:@1]){
                    [aims replaceObjectAtIndex:idx withObject:@0];
                }
            }
        }
    }];
    
    item.tags = [aims copy];
    
    [UIView performWithoutAnimation:^{
        [self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section]];
    }];
        
    switch (indexPath.section) {
        case 0:
            {
                if (indexPath.item != 0) {
                    self.params.sex = @(indexPath.item);
                }
            }
            break;
            case 1:
            {
                if (indexPath.item != 0) {
                    self.params.isFriend = @(indexPath.item);
                }
            }
            break;
            
            case 3:
            {
                ScreenItem *item = self.model.screens[3];
                NSMutableArray *tags = [NSMutableArray array];
                [item.tags enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    
                    if ([obj isEqual:@1]) {
                        
                        BuyMeatPartModel *partModel = self.partModel.position[idx];
                        NSNumber *typeId = partModel.pigPositionId;
                        [tags addObject:typeId];
                    }
                }];
                self.params.pigPositionIds = [tags copy];

            }
            break;
            
            case 4:
            {
                if (indexPath.item != 0) {
                    
                    PigVariety *item = self.pigListModel.list[indexPath.item -1];
                    self.params.varietiesId = item.varietiesId ;
                }
            }
            break;

        default:
            break;
    }
    
//    NSLog(@"点击了 第%ld组 %ld", indexPath.section, indexPath.item);
}


#pragma mark - setter methods

- (void)setIsShowRedView:(BOOL)isShowRedView{
    self.redView.hidden = isShowRedView;
}

- (void)setCross:(BOOL)cross{
    
    NSString *imageStr = cross ?@"switch_show_cross" :@"switch_show_vertical";
    UIImage *image = [UIImage imageNamed:imageStr];
    [self.switchBtn setImage:image forState:UIControlStateNormal];
}

- (void)setPartModel:(BuyMeatPartListModel *)partModel{
    _partModel = partModel;
    self.model.screens = [self obtainScreenData];
}


#pragma mark - getter methods

- (UIImageView *)diamondIcon{
    if (!_diamondIcon) {
        _diamondIcon = [UIImageView makeImageByImageName:@"meat_buy_start" cornerRadius:0];
    }
    return _diamondIcon;
}


- (UIImageView *)recommendedShopIcon{
    if (!_recommendedShopIcon) {
        _recommendedShopIcon = [UIImageView makeImageByImageName:@"meat_buy_recommendIcon" cornerRadius:0];
    }
    return _recommendedShopIcon;
}


- (UIButton *)cartBtn{
    
    if (!_cartBtn) {
        _cartBtn = [UIButton makeButtonWithImageName:@"meat_buy_cart"];
        [_cartBtn addSubview:self.redView];
        
        kWeakSelf(self);
        _cartBtn.tapBlock = ^{
            [weakself dissView];

            if (weakself.dealJumpCartBlock) {
                weakself.dealJumpCartBlock();
            }
        };
    }
    return _cartBtn;
}

- (UIView *)redView{
    
    if (!_redView) {
        _redView = [UIView new];
        _redView.backgroundColor = UIColorFromRGB(0xEE5B5B);
        [self addShadowAndCircleCorner:_redView.layer corner:4];
        _redView.size = CGSizeMake(8, 8);
    }
    return _redView;
}


- (UIButton *)switchBtn{
    
    if (!_switchBtn) {
        _switchBtn = [UIButton makeButtonWithImageName:@"adop_adoplist_selected"];
        
        kWeakSelf(self);
        _switchBtn.tapBlock = ^{
            [weakself dissView];

            if (weakself.dealSwitchShopStyleBlock) {
                weakself.dealSwitchShopStyleBlock();
            }
        };
    }
    return _switchBtn;
}


- (UIButton *)screeningBtn{
    
    if (!_screeningBtn) {
        _screeningBtn = [UIButton makeButtonWithImageName:@"meat_buy_screen_gray"];
        _screeningBtn.selected = NO;
        
        kWeakSelf(self);
        _screeningBtn.tapBlock = ^{
            
            weakself.selected = !weakself.selected;
            UIImage *image = nil;
            
            if (weakself.selected) {
                image = [UIImage imageNamed:@"meat_buy_screen_green"];
                [weakself showView];

                }else{
                    
                image = [UIImage imageNamed:@"meat_buy_screen_gray"];
                [weakself dissView];
            }
            
            [weakself.screeningBtn setImage:image forState:UIControlStateNormal];
            
            if (weakself.dealScreeningBlock) {
                weakself.dealScreeningBlock(weakself.screeningBtn);
                
            }
        };
    }
    return _screeningBtn;
}


- (UIView *)contentView{
    
    if (!_contentView) {
        _contentView = [[UIView alloc] init];
        _contentView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
        _contentView.frame = CGRectMake(0, 0, KScreenWidth, 0);
        _contentView.alpha = 0;
    }
    return _contentView;
}


- (UICollectionViewFlowLayout *)layout{
    
    if (!_layout) {
        _layout = [[UICollectionViewFlowLayout alloc] init];
        
        
        _layout.minimumLineSpacing = mGap;
        _layout.minimumInteritemSpacing = mGap;
        
        _layout.itemSize = CGSizeMake(itemW, 45);
        
        _layout.sectionInset = UIEdgeInsetsMake(mGap, mGap, mGap, mGap);
        _layout.headerReferenceSize = CGSizeMake(KScreenWidth, 40);
        
        _layout.sectionHeadersPinToVisibleBounds = NO;
        
    }
    return _layout;
}


- (UICollectionView *)collectionView{
    
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0) collectionViewLayout:self.layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = KWhiteColor;
        [_collectionView registerClass:[CustomCollectionViewCell class] forCellWithReuseIdentifier:@"CustomCollectionViewCell"];
        [_collectionView registerClass:[CustomSendTimeCollectionCell class] forCellWithReuseIdentifier:@"CustomSendTimeCollectionCell"];
        [_collectionView registerClass:[CustomCollectionSection class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        [_collectionView registerClass:[CustomCollectionFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
        _collectionView.bounces = NO;
        
    }
    return _collectionView;
}

- (NSMutableArray *)dates{
    
    if (!_dates) {
        _dates = [NSMutableArray arrayWithArray:@[@"起始时间",@"结束时间"]];
    }
    return _dates;
}


- (CustomScreenMenuModel *)model{
    
    if(!_model){
        _model = [[CustomScreenMenuModel alloc] init];
    }
    return _model;
}

- (MeatShopListParam *)params{
    
    if (!_params) {
        _params = [[MeatShopListParam alloc] init];
        _params.page = @1;
        _params.limit = @10;
        _params.tribeId = @2;
    }
    return _params;
}

- (NSArray<ScreenItem *> *)obtainScreenData{
    
    NSMutableArray *aims = [NSMutableArray array];
    
    //店主性别
    ScreenItem *shopGenderItem = [[ScreenItem alloc] init];
    shopGenderItem.title = @"店主性别";
    shopGenderItem.subTitles = @[@"全部", @"男", @"女"];
    [aims addObject:shopGenderItem];
    
    ScreenItem *shopAttributedItem = [[ScreenItem alloc] init];
    shopAttributedItem.title = @"店主属性";
    shopAttributedItem.subTitles = @[@"全部", @"好友", @"非好友"];
    [aims addObject:shopAttributedItem];
    
    //发货时间
    ScreenItem *sendTimeItem = [[ScreenItem alloc] init];
    sendTimeItem.title = @"发货时间";
    sendTimeItem.subTitles = @[@"全部"];
    [aims addObject:sendTimeItem];
    

    //部位种类
    ScreenItem *partTypeItem = [[ScreenItem alloc] init];
    partTypeItem.title = @"部位种类";
    NSMutableArray *parts = [NSMutableArray array];
    [self.partModel.position enumerateObjectsUsingBlock:^(BuyMeatPartModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [parts addObject:obj.positionName];
    }];
    
    [parts insertObject:@"全部" atIndex:0];
    partTypeItem.subTitles = [parts copy];
    [aims addObject:partTypeItem];

    
    //猪品种
    ScreenItem *pigTypeItem = [[ScreenItem alloc] init];
    pigTypeItem.title = @"猪品种";
    NSMutableArray *pigList = [NSMutableArray array];
    [self.pigListModel.list enumerateObjectsUsingBlock:^(PigVariety * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [pigList addObject:obj.varietiesName];
    }];
    [pigList insertObject:@"全部" atIndex:0];
    pigTypeItem.subTitles = [pigList copy];
    [aims addObject:pigTypeItem];


    return [aims copy];
}


@end


